#pragma once

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <memory>
#include <filesystem>   // C++17
#include <unistd.h>
#include "Mutex.hpp"



namespace LogModule
{
    using namespace LockModule;

    // 获取当前系统时间
    std::string CurrentTime()
    {
        time_t time_stamp = ::time(nullptr);
        struct tm curr;
        localtime_r(&time_stamp, &curr);
        char buffer[1024];
        snprintf(buffer, sizeof(buffer), "%04d-%02d-%02d %02d:%02d:%02d",
            curr.tm_year + 1900,
            curr.tm_mon + 1,
            curr.tm_mday,
            curr.tm_hour,
            curr.tm_min,
            curr.tm_sec
        );
        return buffer;
    }

    // 日志的默认路径和默认文件名
    const std::string defaultlogpath = "./log/";
    const std::string defaultlogname = "log.txt";

    // 日志等级
    enum class LogLevel
    {
        DEBUG = 1,
        INFO,
        WARNING,
        ERROR,
        FATAL,
    };

    std::string Level2String(LogLevel level)
    {
        switch(level)
        {
            case LogLevel::DEBUG:
                return "DEBUG";
            case LogLevel::INFO:
                return "INFO";
            case LogLevel::WARNING:
                return "WARNING";
            case LogLevel::ERROR:
                return "ERROR";
            case LogLevel::FATAL:
                return "FATAL";
            default:
                return "NONE";
        }
    }

    // 设计模式——策略模式
    class LogStrategy
    {
    public:
        virtual ~LogStrategy() = default;
        virtual void SyncLog(const std::string& message) = 0;  // 纯虚函数
    };

    // 控制台策略
    class ConsoleLogStrategy : public LogStrategy
    {
    public:
        ConsoleLogStrategy(){}
        ~ConsoleLogStrategy(){}
        virtual void SyncLog(const std::string& message)
        {
            LockGuard lockguard(_mutex);
            std::cout << message << std::endl;
        }  
    private:
        Mutex _mutex;
    };

    // 文件级(磁盘)策略
    class FileLogStrategy : public LogStrategy
    {
    public:
        FileLogStrategy(const std::string& logpath = defaultlogpath, const std::string& logname = defaultlogname)
        :_logpath(logpath)
        ,_logname(logname)
        {
            LockGuard lockguard(_mutex);
            // 如果目录存在直接返回，不存在就创建
            if (std::filesystem::exists(_logname))
            {
                return;
            }
            try
            {
                std::filesystem::create_directories(_logpath);
            }
            catch(const std::filesystem::filesystem_error& e)
            {
                std::cerr << e.what() << '\n';
            }
        }
        ~FileLogStrategy(){}
        virtual void SyncLog(const std::string& message)
        {
            LockGuard lockguard(_mutex);
            std::string log = _logpath + _logname;
            std::ofstream out(log, std::ios::app);  // 追加写入
            if (!out.is_open())
            {
                return;
            }
            out << message << "\n";
            out.close();
        }
    private:
        std::string _logpath;
        std::string _logname;
        Mutex _mutex;
    };

    class Logger
    {
    public:
        Logger()
        {
            // 默认采用控制台刷新策略
            _strategy = std::make_shared<ConsoleLogStrategy>();  
        }

        void EnableConsoleLog()
        {
            _strategy = std::make_shared<ConsoleLogStrategy>();
        }

        void EnableFileLog()
        {
            _strategy = std::make_shared<FileLogStrategy>();
        }
        ~Logger(){}

        // [2024-08-04 12:27:03] [DEBUG] [202938] [main.cc] [16] - hello world
        class LogMessage
        {
        public:
            LogMessage(LogLevel level, std::string filename, int line, Logger& logger)
            :_currtime(CurrentTime())
            ,_level(level)
            ,_pid(::getpid())
            ,_filename(filename)
            ,_line(line)
            ,_logger(logger)
            {
                std::stringstream ss;
                ss << "[" << _currtime << "] "
                    << "[" << Level2String(_level) << "] "
                    << "[" << _pid << "] "
                    << "[" << _filename << "] "
                    << "[" << _line << "] - ";
                _loginfo = ss.str();
            }

            template<typename T>
            LogMessage& operator<<(const T& info)
            {
                std::stringstream ss;
                ss << info;
                _loginfo += ss.str();
                return *this;
            }

            ~LogMessage()
            {
                if (_logger._strategy)
                {
                    _logger._strategy->SyncLog(_loginfo);
                }
            }
        private:
            std::string _currtime;  // 时间
            LogLevel _level;        // 日志等级
            pid_t _pid;             // 进程PID
            std::string _filename;  // 源文件名称
            int _line;              // 行号
            Logger& _logger;        // 根据不同刷新策略进行刷新
            std::string _loginfo;   // 一条完整的日志记录
        };

        LogMessage operator()(LogLevel level, const std::string& filename, int line)
        {
            return LogMessage(level, filename, line, *this);
        }
    private:
        std::shared_ptr<LogStrategy> _strategy;  // 日志刷新的策略方案
    };

    Logger logger;

    #define LOG(Level) logger(Level, __FILE__, __LINE__)
    #define ENABLE_CONSOLE_LOG() logger.EnableConsoleLog()
    #define ENABLE_FILE_LOG() logger.EnableFileLog()

}